package com.ruoyi.framework.config;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 开发单位：FESCO Adecco
 * 版权：FESCO Adecco
 *
 * @author：hechunbo
 * @since： JDK1.8
 * @version：1.1
 * @date：2025/8/8 最后更新日期：
 * 修改人：hechunbo
 */
public class CustomWebSocketHandler extends TextWebSocketHandler {

    private static final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String username = Objects.requireNonNull(session.getPrincipal()).getName();
        sessionMap.put(username, session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理客户端发送的消息
        String payload = message.getPayload();
        // 可以在这里添加业务逻辑处理
        session.sendMessage(new TextMessage("服务器收到消息: " + payload));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String username = Objects.requireNonNull(session.getPrincipal()).getName();
        sessionMap.remove(username);
    }

    // 向指定用户发送消息
    public static void sendMessageToUser(String username, String message) throws IOException {
        WebSocketSession session = sessionMap.get(username);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        }
    }
}
